﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using BoutiquePOS.DAL.DAO;
using BoutiquePOS.DAL.Gateway;
using BoutiquePOS.Manager;

namespace BoutiquePOS.UI.UserUI
{
    public partial class PurchaseEntry : System.Web.UI.Page
    {
        SupplierManager supplierManager = new SupplierManager();
        List<Supplier> suppliers = new List<Supplier>();
        Supplier supplier = new Supplier();
        public string SupplierNameList = "";

        ProductCategoryManager productCategoryManager = new ProductCategoryManager();
        List<ProductCategory> productCategories = new List<ProductCategory>();
        PurchaseManager purchaseManager = new PurchaseManager();
        List<PurchaseDtls> purchaseDetailslist = new List<PurchaseDtls>();
        Purchase aPurchase = new Purchase();
        private List<PurchaseDtls> purchaseDtlses = null;
        Product product = new Product();
        public string SuggestionList = "";

        string productName = "";
        decimal tradePrice = 0;
        int qty = 0;
        int freeQty = 0;
        decimal discountPer = 0;
        decimal totalTp = 0;
        decimal totalVat = 0;
        decimal vat = 0;  //new add
        decimal discountAmt = 0;
        decimal netAmt = 0;

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                try
                {
                    string dateAsString = DateTime.Now.ToString("yyyy-MM-dd");
                    purchaseDateTextBox.Value = dateAsString;

                    suppliers = supplierManager.GetAllSupplier();
                    SupplierNameList = supplierManager.GetallSupplierName();

                    messageLebel.Text = "";
                    NextId();

                    LoadProductCategoryDDl();
                    int CategoryId = Convert.ToInt32(productCategoryDDList.SelectedValue); //last change
                    SuggestionList = purchaseManager.GetPurchaseAutoCompleteData(CategoryId); //last change
                    Session["ProductList"] = purchaseDetailslist; //last change
                }
                catch (Exception)
                {
                    messageLebel.Text = "Incorrect information";
                }
            }
        }

        private void LoadProductCategoryDDl()
        {
            productCategories = productCategoryManager.GetAllProductCategory();
            productCategoryDDList.DataTextField = "CategoryName";
            productCategoryDDList.DataValueField = "CategoryId";
            productCategoryDDList.DataSource = productCategories;
            productCategoryDDList.DataBind(); 
        }

        private void NextId()
        {
            try
            {
                string yearAndMonth = GetYearAndMonth();
                string purchaseNo = purchaseManager.NextID(yearAndMonth);
                purchaseNoTextBox.Value = purchaseNo;
            }
            catch (Exception)
            {
                throw;
            }
        }

         private static string GetYearAndMonth()
        {
            try
            {
                DateTime dateTime = DateTime.Now;
                int year = dateTime.Year;
                int month = dateTime.Month;
                string finalMonth = "";
                if (month < 10)
                {
                    finalMonth = "0" + month;
                }
                else
                {
                    finalMonth = month.ToString();
                }
                return year + finalMonth;
            }
            catch (Exception)
            {
                throw;
            }
        }

        protected void productCategoryDDList_SelectedIndexChanged(object sender, EventArgs e)
        {
            try
            {
                int categoryId = Convert.ToInt32(productCategoryDDList.SelectedValue);
                SuggestionList = purchaseManager.GetPurchaseAutoCompleteData(categoryId);
            }
            catch (Exception)
            {
                throw;
            }
        }

        protected void AddtoGridView_Click(object sender, EventArgs e)
        {
            try
            {
                ProductManager productManager = new ProductManager();
                PurchaseDtls purchaseDtls = new PurchaseDtls();
                decimal totalNetAmount = 0;

                productName = productNameTextBox.Value;
                tradePrice = Convert.ToDecimal(tradePriceTextBox.Value);
                qty = Convert.ToInt32(qtyTextBox.Text);
                freeQty = Convert.ToInt32(freeQtyTextBox.Value);
                discountPer = Convert.ToDecimal(discountPercentTextBox.Text);
                totalTp = Convert.ToDecimal(totalTPTextBox.Value);
                totalVat = Convert.ToDecimal(totalVatTextBox.Value);
                discountAmt = Convert.ToDecimal(discountAmtTextBox.Value);
                netAmt = Convert.ToDecimal(netAmtTextBox.Value);


                Product productId = productManager.GetUnitPrice(Convert.ToInt32(productCategoryDDList.SelectedValue), productName);
                productId.ProductBrandName = productName;
                purchaseDtls.AProduct = productId;

                purchaseDtls.TradePrice = tradePrice;
                purchaseDtls.PurchaseQty = qty;
                purchaseDtls.PurchaseFreeQty = freeQty;
                purchaseDtls.DiscountPer = discountPer;
                purchaseDtls.TotalTradePrice = totalTp;
                purchaseDtls.TotalVAt = totalVat;
                purchaseDtls.TotalDiscountAmount = discountAmt;
                purchaseDtls.NetAmount = netAmt;

                purchaseDetailslist = (List<PurchaseDtls>)Session["ProductList"];
                purchaseDetailslist.Add(purchaseDtls);

                purchaseGridView.DataSource = purchaseDetailslist;
                purchaseGridView.DataBind();


                int categoryId = Convert.ToInt32(productCategoryDDList.SelectedValue);
                SuggestionList = purchaseManager.GetPurchaseAutoCompleteData(categoryId);

                foreach (PurchaseDtls purchaseDtlse in purchaseDetailslist)
                {
                    totalNetAmount += purchaseDtlse.NetAmount;
                }

                totalNetAmtTextBox.Value = totalNetAmount.ToString();

                gvClear();

                if (supplierModeDDList.Value == "1")
                {
                    paidAmountTextBox.Text = totalNetAmtTextBox.Value;
                    dueAmtTextBox.Value = "0";
                }
                else
                {
                    paidAmountTextBox.Text = "";
                }
            }
            catch (Exception)
            {
                throw;
            }
        }

        protected void qtyTextBox_TextChanged(object sender, EventArgs e)
        {
            CalculateNetAmount(0);
        }

        private void CalculateNetAmount(decimal dicountPercentage)
        {
            try
            {
                ProductManager productManager = new ProductManager();
                int categoryId = Convert.ToInt32(productCategoryDDList.SelectedValue);
                string productName = productNameTextBox.Value;
                Product product = null;
                product = productManager.GetUnitPrice(categoryId, productName);
                tradePriceTextBox.Value = product.TradePrice.ToString();
                decimal discountAmount = 0;
                decimal totalTp = Convert.ToDecimal(qtyTextBox.Text) * Convert.ToDecimal(tradePriceTextBox.Value);
                if (dicountPercentage <= 0)
                {
                    discountAmount = 0;
                }
                else if (dicountPercentage > 0)
                {
                    discountAmount = totalTp * ((dicountPercentage) / (100));
                }

                decimal totalVat = Convert.ToDecimal(qtyTextBox.Text) * Convert.ToDecimal(product.Vat);

                decimal netAmount = totalTp + discountAmount;
                totalTPTextBox.Value = totalTp.ToString();
                totalVatTextBox.Value = totalVat.ToString();
                discountAmtTextBox.Value = discountAmount.ToString();
                netAmtTextBox.Value = (totalTp - discountAmount + totalVat).ToString();
            }
            catch (Exception)
            {
                throw;
            }
        }

        protected void discountAmtTextBox_TextChanged(object sender, EventArgs e)
        {
            try
            {
                decimal discountPercentage = Convert.ToDecimal(discountPercentTextBox.Text);
                CalculateNetAmount(discountPercentage);
            }
            catch (Exception)
            {
                throw;
            }
        }

        protected void paidAmtTextBox_TextChanged(object sender, EventArgs e)
        {
            try
            {
                decimal dueAmount = Convert.ToDecimal(totalNetAmtTextBox.Value) - Convert.ToDecimal(paidAmountTextBox.Text);
                dueAmtTextBox.Value = dueAmount.ToString();
            }
            catch (Exception)
            {
                throw;
            }
        }

        protected void saveButton_Click(object sender, EventArgs e)
        {
            try
            {
                PurchaseGateway purchaseGateway = new PurchaseGateway();

                string purchaseNo = purchaseNoTextBox.Value;
                string purchaseDate = purchaseDateTextBox.Value;
                string challanNo = challanNoTextBox.Value;
                decimal totalNetAmount = Convert.ToDecimal(totalNetAmtTextBox.Value);

                Purchase aPurchase = new Purchase();
                aPurchase.PurchaseNo = purchaseNo;
                aPurchase.PurchaseDate = purchaseDate;
                aPurchase.ChallanNo = challanNo;
                aPurchase.TotalNetAmount = totalNetAmount;

                Supplier supplier = supplierManager.FindSupplier(supplierNameTextBox.Value);
                aPurchase.ASupplier = supplier;

                purchaseGateway.SavePurchase(aPurchase);

                int id = purchaseGateway.ReturnPurchaseId(aPurchase.PurchaseNo);
                //---------PharPurchase Close------------//
                aPurchase.PurchaseId = id;
                SupplierPayment aSupplierPayment = new SupplierPayment();
                aSupplierPayment.APurchase = aPurchase;
                aSupplierPayment.PaymentDate = purchaseDateTextBox.Value;
                aSupplierPayment.PaidAmount = Convert.ToDecimal(paidAmountTextBox.Text);
                purchaseGateway.SaveSupplierPayment(aSupplierPayment);
                //-----------Supplier Payment Close--------//
                PurchaseDtls aPurchaseDtls = new PurchaseDtls();
                aPurchaseDtls.PurchaseId = id;
                int paymentMode = Convert.ToInt32(supplierModeDDList.Value);

                List<PurchaseDtls> purchaseDtlses = (List<PurchaseDtls>)Session["ProductList"];

                foreach (PurchaseDtls purchaseDtlse in purchaseDtlses)
                {
                    purchaseDtlse.PurchaseId = id;
                    purchaseDtlse.PaymentMode = paymentMode;
                }
                purchaseGateway.SavePurchaseDtls(purchaseDtlses);

                purchaseGridView.DataSource = null;
                purchaseGridView.DataBind();

                clear();
                NextId();
                messageLebel.Text = "Save Successfully";
                //--------------Purchase Dtls Close------------//
            }
            catch (Exception)
            {
                messageLebel.Text = "Incorrect Information.";
            }
        }

        protected void closeButton_Click(object sender, EventArgs e)
        {
            //Response.Redirect("Home.aspx");
        }
        protected void clearButton_Click(object sender, EventArgs e)
        {
            //clear();
        }
        private void clear()
        {
            //purchaseNoTextBox.Value = "";
            //purchaseDateTextBox.Value = "";
            //supplierNameTextBox.Value = "";
            //challanNoTextBox.Value = "";
            //productNameTextBox.Value = "";
            //qtyTextBox.Text = "";
            //tradePriceTextBox.Value = "";
            //discountPercentTextBox.Text = "";
            //totalTPTextBox.Value = "";
            //totalVatTextBox.Value = "";
            //discountAmtTextBox.Value = "";
            //netAmtTextBox.Value = "";
            //totalVatTextBox.Value = "";
            //freeQtyTextBox.Value = "";
            //totalNetAmtTextBox.Value = "";
            //paidAmountTextBox.Text = "";
            //dueAmtTextBox.Value = "";
            //purchaseGridView.DataSource = null;
            //purchaseGridView.DataBind();
        }
        private void gvClear()
        {
            //productNameTextBox.Value = "";
            //qtyTextBox.Text = "";
            //tradePriceTextBox.Value = "";
            //discountPercentTextBox.Text = "";
            //totalTPTextBox.Value = "";
            //totalVatTextBox.Value = "";
            //discountAmtTextBox.Value = "";
            //netAmtTextBox.Value = "";
            //totalVatTextBox.Value = "";
            //freeQtyTextBox.Value = "";
        }


        }
    }
